package com.live.shop.home;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.model.UserModel;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.OkHttpUtils;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.view.ToastBottomUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class FunctionsActivity extends BaseActivity {
    ImageButton fuctions_back;
    RecyclerView fuctions_recyclerview;

    UserDatabase userDb;
    UserModel userModel;
    private JSONArray list = new JSONArray();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_functions);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);

        fuctions_back = findViewById(R.id.fuctions_back);
        fuctions_recyclerview = findViewById(R.id.fuctions_recyclerview);

        fuctions_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();
        getAccount(GetUtil.getAppList(),"",userModel.getToken());
    }

    public static final int RRQUEST_FAILURE = 1;
    public static final int RRQUEST_SUCCESS = 2;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RRQUEST_FAILURE:
                    ToastBottomUtils.Setinfo(getApplicationContext(),msg.obj.toString());
                    break;
                case RRQUEST_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.getInt("code") == 1){
                            if(json.getString("info").equals("查询成功")){
                                list = json.getJSONArray("data");
                                SetListMyValue();
                            }
                        }else{
                            //登录失败
                            ToastBottomUtils.Setinfo(getApplicationContext(),json.getString("info"));
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

    private void SetListMyValue() {
        adapter = new MyAdapter();
        fuctions_recyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        fuctions_recyclerview.setAdapter(adapter);
    }

    private MyAdapter adapter;

    class MyAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyAdapter.MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_function, parent, false));
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            MyAdapter.MyViewHolder mholder = (MyAdapter.MyViewHolder) holder;
            
            try {
                int function_id = list.getJSONObject(position).getInt("function_id");
                String function_name = list.getJSONObject(position).getString("function_name");
                int function_event_code = list.getJSONObject(position).getInt("function_event_code");
                String function_resid = list.getJSONObject(position).getString("function_resid");
                String function_package = list.getJSONObject(position).getString("function_package");

                mholder.item_function_name.setText(function_name);
                if(userModel.getFunctionId() == function_id){
                    mholder.item_function_run.setBackgroundResource(R.drawable.bg_shape_blue_10dip);
                    mholder.item_function_run.setText("已选择");
                    mholder.item_function_run.setTextColor(getColor(R.color.white));
                }else{
                    mholder.item_function_run.setBackgroundResource(R.drawable.bg_shape_gray_10dip);
                    mholder.item_function_run.setText("未选择");
                    mholder.item_function_run.setTextColor(getColor(R.color.black));
                }
                mholder.item_function_run.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        userModel.setFunctionId(function_id);
                        userDb.updateFunctionId(function_id,function_event_code,function_resid,function_package);
                        notifyDataSetChanged();
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public int getItemCount() {
            return list.length();
        }
        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView item_function_name;
            TextView item_function_run;
            public MyViewHolder( View itemView) {
                super(itemView);
                item_function_name = itemView.findViewById(R.id.item_function_name);
                item_function_run = itemView.findViewById(R.id.item_function_run);
            }
        }
    }

    public void getAccount(String url,String jsonStr,String token){
        OkHttpUtils.sendOkHttpJsonTokenRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = RRQUEST_FAILURE;
                message.obj = "【请求异常】请联系管理员";
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseData = response.body().string();
                Message message = new Message();
                message.what = RRQUEST_SUCCESS;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        },token);
    }
}